class CardGame {
  constructor() {
    this.royalDeck = this.createRoyalDeck();
    this.playerDeck = this.createPlayerDeck();
    this.playerHand = [];
    this.discardPile = [];
    this.currentBoss = null;
    this.gameLog = [];
    this.selectedCards = new Set(); // 改为存储卡牌对象
    this.remainingJokers = 2; // 初始小丑次数
    this.initGame();
  }

  createRoyalDeck() {
    const suits = ['♠️', '♥️', '♦️', '♣️'];
    
    // 分层洗牌后合并，确保J在最上层
    const royalHierarchy = {
      J: { hp: 20, atk: 10 },
      Q: { hp: 30, atk: 15 },
      K: { hp: 40, atk: 20 }
    };

    return Object.entries(royalHierarchy)
      .flatMap(([rank, stats]) => {
        const deck = suits.map(suit => ({
          type: 'royal',
          rank,
          suit,
          ...stats
        }));
        this.shuffleDeck(deck);
        return deck;
      });
  }

  log(text) {
    this.gameLog.push(`<div class='log-entry'>🕒 ${text}</div>`);
    const logElement = document.getElementById('game-log');
    logElement.innerHTML = this.gameLog.slice(-8).join('');
    logElement.scrollTop = logElement.scrollHeight;
  }

  showJokerOption() {
    const overlay = document.createElement('div');
    overlay.className = 'joker-overlay';
    overlay.innerHTML = `
      <div class="joker-prompt">
        <h3>使用小鬼能力？</h3>
        <p>剩余次数：${this.remainingJokers}</p>
        <button onclick="game.useJoker(true)">使用</button>
        <button onclick="game.useJoker(false)">取消</button>
      </div>
    `;
    document.body.appendChild(overlay);
  }

  useJoker(confirm) {
    document.querySelector('.joker-overlay').remove();
    if(confirm && this.remainingJokers > 0) {
      this.remainingJokers--;
      this.playerHand = [];
      this.playerHand.push(...this.drawCards(8));
      this.log('🎪 使用小鬼能力！重新抽取手牌');
      this.updateUI();
    } else {
      this.endGame(false);
    }
  }

  initGame() {
    this.shuffleDeck(this.royalDeck);
    this.drawNewBoss();
    this.playerHand = this.drawCards(5);
    this.updateUI();
  }

  drawNewBoss() {
    if(this.royalDeck.length === 0) {
      this.endGame(true);
      return;
    }
    this.currentBoss = this.royalDeck.pop();
    this.log(`遭遇 ${this.currentBoss.rank}${this.currentBoss.suit}！`);
  }

  playTurn() {
    const selectedCards = Array.from(this.selectedCards);
    if(!this.validatePlay(selectedCards)) return;
    
    const totalValue = selectedCards.reduce((sum, card) => {
      return sum + (card.value === 'A' ? 1 : parseInt(card.value));
    }, 0);

    // 处理花色技能
    selectedCards.forEach(card => {
      if(card.suit !== this.currentBoss.suit) {
        this.applySuitEffect(card);
      }
    });

    // 计算伤害
    const damage = selectedCards.some(c => c.suit === '♣️') ? totalValue * 2 : totalValue;
    this.currentBoss.hp -= damage;

    // 检查BOSS状态
    if(this.currentBoss.hp <= 0) {
      this.handleBossDefeat();
    }

    this.updateUI();
  }

  applySuitEffect(card) {
    switch(card.suit) {
      case '♥️':
        this.recoverCards(card.value);
        break;
      case '♦️':
        this.drawCards(card.value);
        break;
      case '♠️':
        this.currentBoss.atk -= card.value;
        break;
    }
  }

  validatePlay(cards) {
    // 验证连招规则
    if(cards.length > 1) {
      const values = cards.map(c => c.value);
      if(new Set(values).size !== 1) return false;
      if(values[0] === 'A') return false;
      if(values.reduce((a,b) => a + parseInt(b), 0) > 10) return false;
    }
    return true;
  }

  updateUI() {
    const handContainer = document.getElementById('hand-container');
    handContainer.innerHTML = '';
    
    this.playerHand.forEach((card, index) => {
      const cardElement = document.createElement('div');
      cardElement.className = `card ${this.selectedCards.has(index) ? 'selected' : ''}`;
      cardElement.innerHTML = `
        <div class="card-value">${card.value}</div>
        <div class="card-suit">${card.suit}</div>
      `;
      cardElement.onclick = () => this.toggleCardSelection(index);
      handContainer.appendChild(cardElement);
    });
    
    document.getElementById('boss-hp').textContent = this.currentBoss.hp;
    document.getElementById('boss-atk').textContent = this.currentBoss.atk;
    document.getElementById('boss-suit').textContent = this.currentBoss.suit;
    document.getElementById('deck-count').textContent = this.playerDeck.length;
    document.getElementById('discard-count').textContent = this.discardPile.length;
  }

  toggleCardSelection(index) {
    const card = this.playerHand[index];
    if (this.selectedCards.has(card)) {
      this.selectedCards.delete(card);
    } else {
      this.selectedCards.add(card);
      document.getElementById('cardSelect').play();
    }
    this.updateUI();
  }

  handleBossDefeat() {
    if (this.currentBoss.hp === 0) {
      document.getElementById('bossDefeat').play();
      this.log(`${this.currentBoss.rank}被感化加入牌堆！`);
      this.playerDeck.unshift(this.currentBoss);
    } else {
      this.log(`击败了${this.currentBoss.rank}${this.currentBoss.suit}！`);
      this.discardPile.push(this.currentBoss);
    }
    this.drawNewBoss();
  }

  createPlayerDeck() {
    const suits = ['♠️', '♥️', '♦️', '♣️'];
    return Array.from({length: 10}, (_, i) => i + 1)
      .flatMap(value => 
        suits.map(suit => ({
          type: 'player',
          value: value.toString(),
          suit,
          isJoker: false
        }))
      ).concat(
        suits.map(suit => ({
          type: 'player',
          value: 'A',
          suit,
          isJoker: false
        }))
      );
  }

  shuffleDeck(deck) {
    for (let i = deck.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [deck[i], deck[j]] = [deck[j], deck[i]];
    }
  }

  handleBossCounterAttack() {
    if (this.currentBoss && this.currentBoss.hp > 0) {
      const requiredValue = this.currentBoss.atk;
      const validCards = this.playerHand.filter(c => parseInt(c.value) >= requiredValue || c.value === 'A');
      
      if (validCards.length === 0 && this.remainingJokers <= 0) {
        this.endGame(false);
        return;
      }
      
      const cardToDiscard = validCards.sort((a, b) => parseInt(a.value) - parseInt(b.value))[0];
      this.discardPile.push(cardToDiscard);
      this.playerHand = this.playerHand.filter(c => c !== cardToDiscard);
      this.log(`被迫弃掉 ${cardToDiscard.value}${cardToDiscard.suit} 抵御攻击！`);
      
      // 自动补牌机制
      const cardsNeeded = 5 - this.playerHand.length;
      if(cardsNeeded > 0) {
        this.playerHand.push(...this.drawCards(cardsNeeded));
      }
    }
  }

  endGame(victory) {
    const overlay = document.createElement('div');
    overlay.className = 'end-game';
    
    // 计算徽章等级（1-3星）
    const badgeLevel = Math.min(Math.floor(this.discardPile.filter(c => c.type === 'royal').length / 4), 3);
    
    overlay.innerHTML = `
      <div class="end-content">
        <h2>${victory ? '胜利！' : '失败...'}</h2>
        <div class="badge-animation level-${badgeLevel}">
          ${'★'.repeat(badgeLevel)}
        </div>
        <p>净化皇室成员：${this.discardPile.filter(c => c.type === 'royal').length}位</p>
        <button onclick="location.reload()">再试一次</button>
      </div>
    `;
    document.body.appendChild(overlay);
  }

  // 修改抽牌逻辑加入小丑触发
  drawCards(count) {
    if(this.playerDeck.length < count && this.remainingJokers > 0) {
      this.showJokerOption();
      return [];
    }
    if(this.playerDeck.length < count) {
      this.playerDeck.push(...this.discardPile);
      this.shuffleDeck(this.playerDeck);
      this.discardPile = [];
      this.log('♻️ 牌堆不足，已回收弃牌堆重新洗牌');
    }
    return Array.from({length: count}, () => this.playerDeck.pop());
  }

  // 添加皇室牌堆验证方法
  validateRoyalDeck() {
    return this.royalDeck.some(c => c.rank === 'J') && 
           this.royalDeck.findIndex(c => c.rank === 'J') > 
           this.royalDeck.findIndex(c => c.rank === 'Q');
  }
}

// 初始化游戏
const game = new CardGame();

// 删除以下重复方法定义
// createRoyalDeck() {
//   return [...this.shuffleDeck(kDeck), ...this.shuffleDeck(qDeck), ...this.shuffleDeck(jDeck)];
// }

// drawCards(count) {
//   if(this.playerDeck.length < count) {
//     this.playerDeck.push(...this.discardPile);
//     this.shuffleDeck(this.playerDeck);
//     this.discardPile = [];
//     this.log('♻️ 牌堆不足，已回收弃牌堆重新洗牌');
//   }
//   return Array.from({length: count}, () => this.playerDeck.pop());
// }